import { SHA1 } from "crypto-js"
import React, { useState } from 'react';
import styles from './login.module.scss'
import { Button, Form, Input, message } from 'antd';
import yzm from "@/assets/yzm.png"
import Tokenstatus from '@/store/token/state'
import { login } from '@/api';
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

/**
 * 登录组件
 * 无参数
 * 无返回值
 */
const encryptPass = (password: string): string => {
  return `*${SHA1(SHA1(password)).toString().toUpperCase()}`;
}
const Login: React.FC = () => {
  const [form] = Form.useForm(); // 初始化表单
  const [loading, setLoading] = useState(false); // 控制提交按钮的加载状态
  const dispatch = useDispatch()
  const navigator = useNavigate()
  /**
   * 验证验证码是否输入
   * @param _ 忽略参数
   * @param value 验证码输入值
   * @returns Promise，如果验证码未输入则reject，否则resolve
   */
  // const validatoryzm = (_:any,value:any) => {
  //   if (!value) {
  //     return Promise.reject(new Error('Please input your 验证码!'));
  //   }
  //   return Promise.resolve();
  // }

  /**
   * 表单提交处理函数
   * @param values 表单提交的值
   * @returns Promise，模拟登录过程
   */
  const onFinish = async (values: any) => {
    try {
      setLoading(true); // 设置按钮加载状态
      const data = {
        name:values.username,
        password:values.password
      }
      data.password = encryptPass(data.password);
      const res = await login(data)
      if (res.code === 0) {
        dispatch({type:Tokenstatus.actionsName.changeToken,token:res.data.token})
        message.success('Login successful!'); // 登录成功提示
        navigator('/')
      }
    } catch (error) {
      message.error('Login failed!'); // 登录失败提示
    } finally {
      setLoading(false); // 重置按钮加载状态
    }
  };
  return (
    <div className={styles.login}>
      <div className={styles.login_item}>
        <Form form={form} onFinish={onFinish} className={styles.form}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: 'Please input your username!' }]}>
            <Input placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}>
            <Input.Password placeholder="Password" />
          </Form.Item>
          {/* <Form.Item
            name="yzm"
            rules={[{ validator: validatoryzm}]}>
            <div className={styles.captchaBox}>
              <Input placeholder="验证码" />
              <img className={styles.captchaImg} src={yzm} alt="" />
            </div>
          </Form.Item> */}
          <Form.Item>
            <Button style={{
              width: '100%',
            }} type="primary" htmlType="submit" loading={loading}>
              Login
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;